package com.yeung.swordoffer;


/**
 * 输入某二叉树的前序遍历和中序遍历的结果，请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
 * 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6}，则重建二叉树并返回。
 */
public class 重建二叉树 {
    public static void main(String[] args) {
        int[] pre = {1, 2, 3, 4, 5, 6, 7};
        int[] in = {3, 2, 4, 1, 6, 5, 7};
        TreeNode treeNode = reConstructBinaryTree(pre, in);
        printPostOrder(treeNode);
    }

    /**
     * 建树
     */
    public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        if (pre == null || in == null || pre.length == 0 || in.length == 0 || pre.length != in.length) {
            return null;
        }
        //二叉树的根节点
        TreeNode root = new TreeNode(pre[0]);
        root.left = null;
        root.right = null;

        //找到根节点在中序序列中的下标位置
        int leftNodeNums = 0;
        for (int i = 0; i < pre.length; i++) {
            if (in[i] == root.val) {
                break;
            }
            leftNodeNums++;
        }
        //找到左子树的前序遍历序列和中序遍历序列
        if (leftNodeNums > 0) {
            //左子树的先序序列
            int[] leftPreOrder = new int[leftNodeNums];
            //左子树的中序序列
            int[] leftInOrder = new int[leftNodeNums];
            for (int i = 0; i < leftNodeNums; i++) {
                leftPreOrder[i] = pre[i + 1];
                leftInOrder[i] = in[i];
            }

            //递归构建左子树
            TreeNode leftRoot = reConstructBinaryTree(leftPreOrder, leftInOrder);
            root.left = leftRoot;

        }

        //找到右子树的节点总数
        int rightNodeNum = in.length - 1 - leftNodeNums;
        if (rightNodeNum > 0) {
            //右子树的先序序列
            int[] rightPreOrder = new int[rightNodeNum];
            //右子树的中序序列
            int[] rightInOrder = new int[rightNodeNum];

            for (int i = 0; i < rightNodeNum; i++) {
                rightPreOrder[i] = pre[leftNodeNums + 1 + i];
                rightInOrder[i] = in[leftNodeNums + 1 + i];
            }
            // 递归构建右子树
            TreeNode rightRoot = reConstructBinaryTree(rightPreOrder, rightInOrder); // 递归构建右子树
            root.right = rightRoot;
        }

        return root;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    /**
     * 后序遍历二叉树（递归实现）
     */
    public static void printPostOrder(TreeNode root) {
        if (root != null) {
            //遍历左子树
            printPostOrder(root.left);
            //遍历右子树
            printPostOrder(root.right);
            //完成左右子树遍历, 输出根节点值
            System.out.println(root.val);
        }
    }

}
